package com.hualian.util.http;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 获取request中请求参数,封装成map返回
 * @author felix
 *
 */
public class RequestUtil {
	
	/**
	 * 获取request中请求参数,封装成map返回
	 * @param request
	 * @return
	 */
	public static final Map<String,Object> convertParamToMap(HttpServletRequest request){
		Map<String,Object> param=new HashMap<String, Object>();
		Enumeration<String> e=request.getParameterNames();
		String name="";
		String str[]=null;
		while(e.hasMoreElements()){
			name=e.nextElement();
			str=request.getParameterValues(name);
			name=name.replace("[", "").replace("]", "");
			if(str.length==1)
				param.put(name, str[0].replaceAll("\"", "\\\"").replaceAll("\'", "\\\'").replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
			else{
				for(int i=0;i<str.length;i++)
					str[i]=str[i].replaceAll("\"", "\\\"").replaceAll("\'", "\\\'").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
				param.put(name, str);
			}
		}
		return param;
	}
	
	/**
	 * 获取用户真实ip
	 * @param request
	 */
	public static final String getRealIp(HttpServletRequest request){
		String ip=request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip=request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip=request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip=request.getRemoteAddr();
		}
		return ip;
	}
	
	/**
	 * 获取用户id
	 * @param session
	 * @return
	 */
	public static final Object getUserId(HttpSession session){
		return session.getAttribute("userId");
	}
	
	/**
	 * 获取用户角色
	 * @param session
	 * @return
	 */
	public static final Set<String> getUserRoles(HttpSession session){
		Set<String> roles=null;
		Object obj=session.getAttribute("roles");
		if(obj==null){
			roles=new HashSet<String>();
			roles.add("-1");
		}else{
			roles=(Set<String>)obj;
		}
		return roles;
	}
}
